import 'package:flutter/material.dart';
import 'package:flutter_card_banner/flutter_card_banner.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Card Banner Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Card Banner Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 轮播设置
  bool _autoPlay = true;
  bool _loop = true;
  int _duration = 3000;
  int _animationDuration = 800;
  int _currentPage = 0;

  // 创建控制器
  final CardBannerController _controller = CardBannerController();
  // 选择目标页面
  int _targetPage = 0;

  // 创建一些演示卡片
  final List<Widget> _demoCards = [
    _buildCard(Colors.blue, '卡片 1', Icons.favorite, '正面'),
    _buildCard(Colors.red, '卡片 2', Icons.star, '正面'),
    _buildCard(Colors.green, '卡片 3', Icons.camera, '正面'),
    _buildCard(Colors.orange, '卡片 4', Icons.music_note, '正面'),
    _buildCard(Colors.purple, '卡片 5', Icons.bubble_chart, '正面'),
  ];

  // 为了演示效果，让我们也创建背面卡片，供用户查看翻转效果
  final List<Widget> _demoCardsBacks = [
    _buildCard(Colors.blue.shade900, '卡片 1', Icons.favorite_border, '背面'),
    _buildCard(Colors.red.shade900, '卡片 2', Icons.star_border, '背面'),
    _buildCard(Colors.green.shade900, '卡片 3', Icons.camera_alt, '背面'),
    _buildCard(Colors.orange.shade900, '卡片 4', Icons.music_note_outlined, '背面'),
    _buildCard(
        Colors.purple.shade900, '卡片 5', Icons.bubble_chart_outlined, '背面'),
  ];

  // 组合正反面卡片，index偶数为正面，奇数为背面
  List<Widget> get _combinedCards {
    List<Widget> cards = [];
    for (int i = 0; i < _demoCards.length; i++) {
      cards.add(_demoCards[i]);
    }
    return cards;
  }

  static Widget _buildCard(
      Color color, String text, IconData icon, String position) {
    return Card(
      elevation: 4,
      color: color,
      child: Container(
        width: double.infinity,
        height: double.infinity,
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 80,
              color: Colors.white,
            ),
            const SizedBox(height: 20),
            Text(
              text,
              style: const TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              position,
              style: const TextStyle(
                fontSize: 16,
                color: Colors.white70,
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          // 卡片轮播组件
          Container(
            height: 300,
            margin: const EdgeInsets.all(16),
            child: CardBanner(
              children: _demoCards,
              backSideChildren: _demoCards,
              controller: _controller,
              autoPlay: _autoPlay,
              loop: _loop,
              duration: _duration,
              animationDuration: _animationDuration,
              onPageChanged: (page) {
                setState(() {
                  _currentPage = page;
                });
              },
              padding: const EdgeInsets.all(8),
            ),
          ),

          // 控制面板
          Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('当前页: ${_currentPage + 1}/${_demoCards.length}',
                        style: const TextStyle(
                            fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 20),

                    // 添加页面控制按钮
                    Card(
                      elevation: 2,
                      child: Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text('控制翻页：',
                                style: TextStyle(
                                    fontSize: 16, fontWeight: FontWeight.bold)),
                            const SizedBox(height: 12),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                ElevatedButton(
                                    onPressed: () => _controller.previousPage(),
                                    child: const Text('上一页')),
                                ElevatedButton(
                                    onPressed: () => _controller.nextPage(),
                                    child: const Text('下一页')),
                              ],
                            ),
                            const SizedBox(height: 12),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                ElevatedButton(
                                    onPressed: () => _controller.jumpToPage(0),
                                    child: const Text('跳转到第1页')),
                                ElevatedButton(
                                    onPressed: () =>
                                        _controller.animateToPage(2),
                                    child: const Text('动画到第3页')),
                              ],
                            ),
                            const SizedBox(height: 12),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                ElevatedButton(
                                    onPressed: () =>
                                        _controller.startAutoPlay(),
                                    style: ElevatedButton.styleFrom(
                                      primary: Colors.green,
                                    ),
                                    child: const Text('开始自动播放')),
                                ElevatedButton(
                                    onPressed: () => _controller.stopAutoPlay(),
                                    style: ElevatedButton.styleFrom(
                                      primary: Colors.red,
                                    ),
                                    child: const Text('停止自动播放')),
                              ],
                            ),
                            const SizedBox(height: 12),
                            // 目标页面选择器
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text('选择目标页面:'),
                                Row(
                                  children: [
                                    Expanded(
                                      child: Slider(
                                        min: 0,
                                        max: (_demoCards.length - 1).toDouble(),
                                        divisions: _demoCards.length - 1,
                                        value: _targetPage.toDouble(),
                                        label: '${_targetPage + 1}',
                                        onChanged: (value) {
                                          setState(() {
                                            _targetPage = value.round();
                                          });
                                        },
                                      ),
                                    ),
                                    Text('${_targetPage + 1}'),
                                    const SizedBox(width: 8),
                                    ElevatedButton(
                                        onPressed: () => _controller
                                            .animateToPage(_targetPage),
                                        child: const Text('前往')),
                                  ],
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),

                    const SizedBox(height: 16),

                    // 自动播放开关
                    Row(
                      children: [
                        const Text('自动播放: ', style: TextStyle(fontSize: 16)),
                        Switch(
                          value: _autoPlay,
                          onChanged: (value) {
                            setState(() {
                              _autoPlay = value;
                            });
                          },
                        ),
                      ],
                    ),

                    // 循环模式开关
                    Row(
                      children: [
                        const Text('循环模式: ', style: TextStyle(fontSize: 16)),
                        Switch(
                          value: _loop,
                          onChanged: (value) {
                            setState(() {
                              _loop = value;
                            });
                          },
                        ),
                      ],
                    ),

                    // 停留时间滑块
                    Row(
                      children: [
                        const Text('停留时间: ', style: TextStyle(fontSize: 16)),
                        Expanded(
                          child: Slider(
                            min: 1000,
                            max: 5000,
                            divisions: 8,
                            value: _duration.toDouble(),
                            label: '${_duration}ms',
                            onChanged: (value) {
                              setState(() {
                                _duration = value.round();
                              });
                            },
                          ),
                        ),
                        Text('${_duration}ms',
                            style: const TextStyle(fontSize: 14)),
                      ],
                    ),

                    // 动画时间滑块
                    Row(
                      children: [
                        const Text('动画时间: ', style: TextStyle(fontSize: 16)),
                        Expanded(
                          child: Slider(
                            min: 500,
                            max: 2000,
                            divisions: 6,
                            value: _animationDuration.toDouble(),
                            label: '${_animationDuration}ms',
                            onChanged: (value) {
                              setState(() {
                                _animationDuration = value.round();
                              });
                            },
                          ),
                        ),
                        Text('${_animationDuration}ms',
                            style: const TextStyle(fontSize: 14)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
